<template>
  <AxiomDialog
    :model-value="visible"
    :title="title"
    width="500px"
    @close="handleClose"
    @cancel="handleClose"
    @confirm="handleConfirm"
    :confirm-loading="loading"
  >
    <AxiomForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <AxiomFormItem label="用户名" prop="username">
        <AxiomInput v-model="formData.username" :disabled="isEdit" placeholder="请输入用户名" />
      </AxiomFormItem>
      <AxiomFormItem v-if="!isEdit" label="密码" prop="password">
        <AxiomInput v-model="formData.password" type="password" placeholder="请输入密码" />
      </AxiomFormItem>
      <AxiomFormItem label="昵称" prop="nickname">
        <AxiomInput v-model="formData.nickname" placeholder="请输入昵称" />
      </AxiomFormItem>
      <AxiomFormItem label="邮箱" prop="email">
        <AxiomInput v-model="formData.email" placeholder="请输入邮箱" />
      </AxiomFormItem>
      <AxiomFormItem label="状态" prop="status">
        <AxiomRadioGroup v-model="formData.status" :options="statusOptions" />
      </AxiomFormItem>
    </AxiomForm>
  </AxiomDialog>
</template>

<script setup>
import { ref, reactive, computed, watch, inject } from 'vue';
import {
  AxiomDialog,
  AxiomFormItem,
  AxiomInput,
  AxiomForm,
  AxiomRadioGroup,
} from 'axiom-view';
import { createUser, updateUser } from '@/api/system/user';

const props = defineProps({
  visible: Boolean,
  mode: {
    type: String,
    default: 'add',
  },
  initialData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['close', 'success']);
const { notification } = inject('axiom-utils');
const formRef = ref(null);

const defaultFormData = {
  username: '',
  password: '',
  nickname: '',
  email: null,
  status: 1,
};

const loading = ref(false);
const formData = reactive({ ...defaultFormData });

const statusOptions = ref([
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 },
]);

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名至少需要3个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少为6位', trigger: 'blur' },
  ],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
});

const isEdit = computed(() => props.mode === 'edit');
const title = computed(() => (isEdit.value ? '编辑用户' : '新增用户'));

watch(() => props.visible, (val) => {
  if (val) {
    Object.assign(formData, { ...defaultFormData, ...props.initialData });
  }
});

const handleClose = () => {
  Object.assign(formData, { ...defaultFormData });
  if (formRef.value) {
    formRef.value.resetFields();
  }
  emit('close');
};

const handleConfirm = async () => {
  try {
    if (!formRef.value) return;
    const valid = await formRef.value.validate();
    if (!valid) return;

    loading.value = true;
    
    // [修复] 在提交前处理 email 字段，将空字符串转换为 null
    const payload = { ...formData };
    if (payload.email === '') {
      payload.email = null;
    }
    
    if (isEdit.value) {
      // 在编辑模式下，只提交允许修改的字段
      const updatePayload = {
        nickname: payload.nickname,
        email: payload.email,
        status: payload.status,
      };
      await updateUser(payload.id, updatePayload);
      notification.success({ title: '成功', message: '更新成功' });
    } else {
      await createUser(payload);
      notification.success({ title: '成功', message: '创建成功' });
    }
    emit('success');
    handleClose();
  } catch (error) {
    console.error('用户表单提交失败:', error);
  } finally {
    loading.value = false;
  }
};
</script> 